import React, { useState, useRef, useEffect } from 'react';
import { createPortal } from 'react-dom';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import { getDynamicFonts } from '@/utils/fontUtils';
import { useMessage } from '@/components/messageApi';

// 排序选项类型定义
export type SortOption = 'newest' | 'oldest';

// 排序选项配置（基于完成时间）
export const SORT_OPTIONS = [
    { key: 'newest' as const, labelKey: 'collection.sortNewest' },
    { key: 'oldest' as const, labelKey: 'collection.sortOldest' }
];

interface CollectionHeaderProps {
    sortBy: SortOption;
    onSortChange: (sortBy: SortOption) => void;
    userInfo?: {
        avatar: string;
        username: string;
    };
    // 添加管理模式相关属性
    isManageMode?: boolean;
    onManageModeChange?: (isManageMode: boolean) => void;
    selectedCount?: number;
    onDeleteSelected?: () => void;
}

/**
 * 图片收藏页面头部组件
 */
const CollectionHeader: React.FC<CollectionHeaderProps> = ({
    sortBy,
    onSortChange,
    userInfo,
    isManageMode = false,
    onManageModeChange,
    selectedCount = 0,
    onDeleteSelected
}) => {
    const { t, i18n } = useTranslation();
    const dynamicFonts = getDynamicFonts(i18n);
    const navigate = useNavigate();
    const message = useMessage();
    const [isDropdownOpen, setIsDropdownOpen] = useState(false);
    const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
    const dropdownRef = useRef<HTMLDivElement>(null);

    // 点击外部关闭下拉框
    useEffect(() => {
        const handleClickOutside = (event: MouseEvent) => {
            if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
                setIsDropdownOpen(false);
            }
        };

        document.addEventListener('mousedown', handleClickOutside);
        return () => {
            document.removeEventListener('mousedown', handleClickOutside);
        };
    }, []);

    // 防止弹窗打开时背景滚动
    useEffect(() => {
        if (showDeleteConfirm) {
            // 禁用背景滚动
            const originalStyle = window.getComputedStyle(document.body).overflow;
            document.body.style.overflow = 'hidden';

            return () => {
                // 恢复背景滚动
                document.body.style.overflow = originalStyle;
            };
        }
    }, [showDeleteConfirm]);

    /**
     * 获取当前选中的排序选项标签
     */
    const getCurrentSortLabel = () => {
        const option = SORT_OPTIONS.find(opt => opt.key === sortBy);
        return option ? t(option.labelKey) : t('collection.sortBy');
    };

    /**
     * 处理排序选项点击
     */
    const handleSortOptionClick = (option: SortOption) => {
        onSortChange(option);
        setIsDropdownOpen(false);
    };

    /**
     * 处理标题点击，返回图片生成页面
     */
    const handleTitleClick = () => {
        navigate('/collections');
    };

    /**
     * 处理管理模式切换
     */
    const handleManageModeToggle = () => {
        if (onManageModeChange) {
            onManageModeChange(!isManageMode);
        }
    };

    /**
     * 处理删除按钮点击
     */
    const handleDeleteClick = () => {
        if (selectedCount === 0) {
            message.warning(t('collection.selectImages'));
            return;
        }
        setShowDeleteConfirm(true);
    };

    /**
     * 确认删除
     */
    const handleConfirmDelete = () => {
        setShowDeleteConfirm(false);
        if (onDeleteSelected) {
            onDeleteSelected();
        }
    };

    /**
     * 取消删除
     */
    const handleCancelDelete = () => {
        setShowDeleteConfirm(false);
    };

    return (
        <div
            className="flex items-center justify-between 
                       px-3 sm:px-6 md:px-8  py-3 sm:py-4 
                       bg-[rgb(19,19,19)] border-b border-[rgb(51,51,57)]"
        >
            {/* 左侧：标题和用户信息 */}
            <div className="flex items-center gap-2 sm:gap-4 min-w-0 flex-1">
                {/* 返回按钮 */}
                <button
                    onClick={handleTitleClick}
                    className="flex items-center justify-center w-8 h-8 sm:w-10 sm:h-10 rounded-full hover:bg-gray-800 transition-colors text-white"
                    aria-label={t('common.back')}
                    style={{ fontFamily: dynamicFonts.font4 }}
                >
                    <i className="fas fa-arrow-left text-lg sm:text-xl" />
                </button>
                {/* 标题 */}
                {/* <h1
                    className="text-lg sm:text-xl md:text-2xl font-semibold text-white cursor-pointer hover:text-pink-400 transition-colors duration-200 truncate"
                    style={{ fontFamily: dynamicFonts.font4 }}
                    onClick={handleTitleClick}
                >
                    {t('collection.title')}
                </h1> */}

                {/* 用户信息 */}
                {userInfo && (
                    <div className="flex items-center gap-2 sm:gap-3 min-w-0">
                        {/* 用户头像 */}
                        <div className="w-8 h-8 sm:w-10 sm:h-10 rounded-full overflow-hidden flex-shrink-0">
                            <img
                                src={userInfo.avatar}
                                alt={userInfo.username}
                                className="w-full h-full object-cover"
                                style={{ objectPosition: 'center top' }}
                                onError={(e) => {
                                    // 头像加载失败时显示默认头像
                                    const target = e.target as HTMLImageElement;
                                    target.src = '';
                                }}
                            />
                        </div>

                        {/* 用户名 */}
                        <span className="text-white font-medium text-sm sm:text-base md:text-lg truncate max-w-[120px] sm:max-w-none" style={{ fontFamily: dynamicFonts.font1 }}>
                            {userInfo.username}
                        </span>
                    </div>
                )}
            </div>

            {/* 右侧操作区域 */}
            <div className="flex items-center gap-2 sm:gap-3 flex-shrink-0">
                {/* 管理模式下的操作按钮 */}
                {isManageMode ? (
                    <>
                        {/* 选择计数 */}
                        {selectedCount > 0 && (
                            <span className="text-pink-500 text-xs sm:text-sm md:text-[0.9rem] font-medium">
                                {t('collection.selected', { count: selectedCount })}
                            </span>
                        )}

                        {/* 删除按钮 */}
                        <button
                            onClick={handleDeleteClick}
                            className={`px-2 sm:px-3 md:px-4 py-1.5 sm:py-2 text-xs sm:text-sm md:text-[0.9rem] rounded-lg transition-colors ${selectedCount > 0
                                ? 'bg-red-600 hover:bg-red-700 text-white'
                                : 'bg-gray-600 text-gray-400 cursor-not-allowed'
                                }`}
                            disabled={selectedCount === 0}
                            style={{ fontFamily: dynamicFonts.font3 }}
                        >
                            {t('collection.delete')}
                        </button>

                        {/* 取消按钮 */}
                        <button
                            onClick={handleManageModeToggle}
                            className="px-2 sm:px-3 md:px-4 py-1.5 sm:py-2 text-xs sm:text-sm md:text-[0.9rem] 
                                       text-white border border-gray-600 rounded-lg hover:bg-gray-800 transition-colors"
                            style={{ fontFamily: dynamicFonts.font3 }}
                        >
                            {t('collection.cancel')}
                        </button>
                    </>
                ) : (
                    <>
                        {/* 管理按钮 */}
                        <button
                            onClick={handleManageModeToggle}
                            className="px-2 sm:px-3 md:px-4 py-1.5 sm:py-2 text-xs sm:text-sm md:text-[0.9rem] 
                                       text-white border border-gray-600 rounded-lg hover:bg-gray-800 transition-colors"
                            style={{ fontFamily: dynamicFonts.font3 }}
                        >
                            <i className="fas fa-cog mr-1 sm:mr-2" />
                            {t('collection.manage')}
                        </button>

                        {/* 排序下拉框 */}
                        <div className="relative" ref={dropdownRef}>
                            <button
                                onClick={() => setIsDropdownOpen(!isDropdownOpen)}
                                className="flex text-xs sm:text-sm md:text-[0.9rem] items-center gap-1 sm:gap-2 
                                           px-2 sm:px-3 md:px-4 py-1.5 sm:py-2 text-white border border-gray-600 
                                           rounded-lg min-w-0 hover:bg-gray-800 transition-colors"
                            >
                                <span
                                    style={{ fontFamily: dynamicFonts.font3 }}
                                    className="truncate max-w-[80px] sm:max-w-none"
                                >
                                    {getCurrentSortLabel()}
                                </span>
                                <i className={`fas fa-chevron-${isDropdownOpen ? 'up' : 'down'} text-xs sm:text-sm flex-shrink-0`} />
                            </button>

                            {/* 下拉菜单 */}
                            {isDropdownOpen && (
                                <div className="absolute right-0 top-full mt-1 w-32 sm:w-36 md:w-40
                                 bg-[rgb(29,29,30)] rounded-lg shadow-lg z-10">
                                    {SORT_OPTIONS.map((option, index) => (
                                        <div key={option.key} style={{ fontFamily: dynamicFonts.font3, color: "white", borderBottom: index === SORT_OPTIONS.length - 1 ? "none" : "1px solid rgb(51,51,57)" }}>
                                            <button
                                                onClick={() => handleSortOptionClick(option.key)}
                                                className="w-full flex items-center gap-2 sm:gap-3 px-2 sm:px-3 md:px-4 py-2 sm:py-2.5 md:py-3 text-left hover:bg-gray-800  transition-colors"
                                            >
                                                {/* 选中状态的粉红色勾选图标 */}
                                                <div className="w-3 h-3 sm:w-4 sm:h-4 flex items-center justify-center flex-shrink-0">
                                                    {sortBy === option.key && (
                                                        <i className="fas fa-check text-pink-500 text-xs sm:text-sm" />
                                                    )}
                                                </div>
                                                <span className="text-xs sm:text-sm md:text-[0.9rem] truncate">
                                                    {t(option.labelKey)}
                                                </span>
                                            </button>
                                        </div>
                                    ))}
                                </div>
                            )}
                        </div>
                    </>
                )}
            </div>

            {/* 删除确认对话框 - 使用Portal渲染到body */}
            {showDeleteConfirm && createPortal(
                <div
                    className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4"
                    style={{ zIndex: 9999 }}
                    onClick={(e) => {
                        // 点击背景关闭弹窗
                        if (e.target === e.currentTarget) {
                            handleCancelDelete();
                        }
                    }}
                >
                    <div
                        className="bg-[rgb(29,29,30)] rounded-lg p-4 sm:p-6 w-full max-w-md mx-auto shadow-2xl"
                        onClick={(e) => e.stopPropagation()}
                    >
                        <div className="text-center">
                            {/* 标题 */}
                            <h3 className="text-lg sm:text-xl font-semibold text-white mb-3 sm:mb-4"
                                style={{ fontFamily: dynamicFonts.font4 }}>
                                {t('collection.deleteConfirmTitle')}
                            </h3>

                            {/* 确认消息 */}
                            <p className="text-gray-300 text-sm sm:text-base mb-6 sm:mb-8"
                                style={{ fontFamily: dynamicFonts.font1 }}>
                                {t('collection.deleteConfirmMessage')}
                            </p>

                            {/* 按钮 */}
                            <div className="flex gap-3 sm:gap-4 justify-center">
                                <button
                                    onClick={handleCancelDelete}
                                    className="px-4 sm:px-6 py-2 sm:py-2.5 text-sm sm:text-base text-white 
                                               border border-gray-600 rounded-lg hover:bg-gray-800 transition-colors flex-1 sm:flex-none"
                                    style={{ fontFamily: dynamicFonts.font3 }}
                                >
                                    {t('collection.cancel')}
                                </button>
                                <button
                                    onClick={handleConfirmDelete}
                                    className="px-4 sm:px-6 py-2 sm:py-2.5 text-sm sm:text-base text-white 
                                               bg-red-600 hover:bg-red-700 rounded-lg transition-colors flex-1 sm:flex-none"
                                    style={{ fontFamily: dynamicFonts.font3 }}
                                >
                                    {t('collection.confirm')}
                                </button>
                            </div>
                        </div>
                    </div>
                </div>,
                document.body
            )}
        </div>
    );
};

export default CollectionHeader; 